
export class FileBeatInstance {
  
  constructor(ip, data = {}) {
    this.ip = ip
    this.setData(data)
  }

  setData(data) {
    const { beat, libbeat, system  } = data
    this.rawData = data
    this.status = data.beat ? '正常': '异常'
    this.time = new Date().getTime()
    // 内存使用
    this.memory = forMatMemory(beat?.memstats?.memory_alloc || 0)
    // 输出类型
    this.outputType = libbeat?.output?.type || '未知'
    // 系统负载
    this.systemCpuLoad = forMatCpuLoad(system?.load['1'] || 0)
    this.uptime = formatDuration(beat?.info?.uptime?.ms || 0)
    this.version = beat?.info?.version || '未知'
  }

  setTime(time) {
    this.time = new Date(time).getTime()
  }
}

export const forMatMemory = (memory) => {
  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
  let index = 0
  while (memory > 1024) {
    memory /= 1024
    index += 1
  }
  return `${memory.toFixed(2)} ${units[index]}`
} 
function convertMilliseconds(ms) {
  const SECOND = 1000;
  const MINUTE = 60 * SECOND
  const HOUR = 60 * MINUTE
  const DAY = 24 * HOUR

  const days = Math.floor(ms / DAY)
  const hours = Math.floor((ms % DAY) / HOUR)
  const minutes = Math.floor((ms % HOUR) / MINUTE)
  const seconds = Math.floor((ms % MINUTE) / SECOND)

  return {
    days,
    hours,
    minutes,
    seconds
  }
}

export function formatDuration(ms) {
  const { days, hours, minutes, seconds } = convertMilliseconds(ms)
  let result = ''
  if (days > 0) {
    result += `${days}天`
  }
  if (hours > 0) {
    result += `${hours}小时`
  }
  if (minutes > 0) {
    result += `${minutes}分钟`
  }
  result += `${seconds}秒`
  return result
}

export const forMatCpuLoad = (load) => {
  return `${(load).toFixed(2)} %`
} 

export function chunkArray(array, chunkSize) {
  const chunks = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    chunks.push(array.slice(i, i + chunkSize));
  }
  return chunks;
}



